#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar cs1, cs2, num1, num2;  
uchar code table[] = {0, 1};

sbit qdg = P3^4;  // 启动信号
sbit xdg = P3^5;  // 停止信号
sbit in1 = P1^0;
sbit in2 = P1^1;
sbit in3 = P1^2;
sbit in4 = P1^3;
sbit ena = P1^4;  // 电机a使能
sbit enb = P1^5;  // 电机b使能

void delay(unsigned int z)
{
    unsigned int x, y;
    for(x = z; x > 0; x--)
        for(y = 110; y > 0; y--);
}  // 优化延时参数

void init()
{
    TMOD = 0x11;  
    TH0 = (65536 - 500) / 256;  // 修正初值计算
    TL0 = (65536 - 500) % 256;
    ET0 = 1;      // 允许定时器0中断
    TR0 = 1;      // 启动定时器0
    EA = 1;       // 开启总中断
}

void main()
{
    init();
    
    while(1)  
    {
        if(qdg == 1)  // 启动条件
        {
            ena = 1;
            enb = 1;
            in2 = 0;
            in4 = 0;
        }
        else  // 停止条件
        {
            ena = 0;
            delay(1000);
            ena = 1;
        }
        
        if(xdg == 0)  // 紧急停止
        {
            in2 = 1;
            in4 = 1;
            delay(1000);
            ena = 0;
            delay(1000);
        }
    }
}

void timer0() interrupt 1  
{
    TH0 = (65536 - 500) / 256;
    TL0 = (65536 - 500) % 256;
    
    cs1++;
    if(cs1 == 10)
    {
        cs1 = 0;
        num1++;
        if(num1 == 3)
            num1 = 0;
        in1 = table[num1];
        
        num2++;
        if(num2 == 3)
            num2 = 0;
        in3 = table[num2];
    }
}